package com.kelvem.saas.workbanch.core.utils;

import com.kelvem.saas.workbanch.core.exception.ErrorCodeEnum;
import com.kelvem.saas.workbanch.core.exception.GlobalExceptionHandler;
import com.kelvem.saas.workbanch.core.exception.SaasException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class ServletUtils {

    private ServletUtils() {}

    public static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            return request;
        }
        return null;
    }

    public static HttpServletResponse getHttpServletResponse() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null;
        }
        return attributes.getResponse();
    }

    public static void writeResponse(ErrorCodeEnum errorCodeEnum, Exception e) {
        try {
            String description = e == null ? "" : e.toString();
            GlobalExceptionHandler.ErrorDetails detail = new GlobalExceptionHandler.ErrorDetails(
                    errorCodeEnum.getCode(),
                    errorCodeEnum.getMessage(),
                    description
            );

            HttpServletResponse httpResponse = getHttpServletResponse();
            if (httpResponse == null) {
                throw new SaasException(ErrorCodeEnum.COMMON_OBJECT_NULL);
            }
            httpResponse.setContentType("application/json");
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.getWriter().write(detail.toString());
            httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } catch (Exception ex) {
            throw new SaasException("writeResponse err", ex);
        }
    }

    public static String getClientIP() {
        HttpServletRequest request = getHttpServletRequest();
        if (request == null) {
            return null;
        }
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果经过多个代理服务器，获取第一个非 unknown 的 IP 地址
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(0, ip.indexOf(",")).trim();
        }
        return ip;
    }

    public static String getRequestURI() {
        HttpServletRequest request = getHttpServletRequest();
        if (request == null) {
            return null;
        }
        return request.getRequestURI();
    }
}
